package figure8.GUI;

import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EtchedBorder;

import figure8.Controller;
import figure8.LoopTiming;
import figure8.Project;

public class ProjectAlreadyExistsWindow extends JDialog {
	public ProjectAlreadyExistsWindow(final Controller controller, final File directory, final String name, final LoopTiming timing)
	{
		this.setLocation(controller.getWindow().getFrame().getX() + 80, controller.getWindow().getFrame()
				.getY() + 120);
		
		final JDialog warningWindow = this;	
		JPanel panel = new JPanel(new GridLayout(3,1));
		panel.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));
		this.getContentPane().add(panel);
		this.setIconImage(Toolkit.getDefaultToolkit().getImage("src/figure8/GUI/Fig8-small.png"));
		this.setAlwaysOnTop(true);
		
		panel.add(new JLabel("A project with this name already exists."));
		panel.add(new JLabel("It will be overwritten. Are you sure you wish to do this?"));

		JPanel buttons = new JPanel(new GridLayout(1,2));
		JButton yes = new JButton("Yes");
		yes.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				try {
					File projectDir = new File(directory + File.separator + name);
					File[] filesInDir = projectDir.listFiles();
					File[] recordings = new File(projectDir + "/Recordings/").listFiles();
					for(File recording : recordings) 
					{
						if(recording.delete() == false) {
								System.err.println(recording.getAbsolutePath() + " failed to delete.");
						}
					}
					for(File fileFound : filesInDir) 
					{
						if(fileFound.delete() == false) {
								System.err.println(fileFound.getAbsolutePath() + " failed to delete.");
						}
					}
					controller.setProject(new Project(timing, name, directory));
				} catch(Exception e) {
					e.printStackTrace();
				}
				warningWindow.dispose();
			}
		});
		buttons.add(yes);
		JButton no = new JButton("No");
		no.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				warningWindow.dispose();
			}
		});
		buttons.add(no);
		panel.add(buttons);

		this.pack();
		this.setVisible(true);
	}
}